import json

import requests
from virus_mysql_helper import *

db_con = get_connection()
db_cursor = get_cursor(db_con)


def get_page():
    """
    爬取疫情数据
    """
    url = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
    headers = {
        'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36'
    }
    r = requests.get(url, headers)
    res = json.loads(r.text)
    data_res = json.loads(res['data'])
    return data_res


def main():
    """主函数"""
    json_data = get_page()
    last_time = json_data['lastUpdateTime']
    print('最新更新时间', last_time)

    # 获取最新的当天数据
    record_date = json_data['lastUpdateTime'][:10]
    today_total = json_data['chinaTotal']
    today_add = json_data['chinaAdd']
    print('今天总数据:', str(today_total))
    print('今天新增数据:', str(today_add))

    # 查询当前时间的数据
    result = get_today_data(db_con, db_cursor, last_time)
    if len(result) > 0:
        # 已经有最新数据
        pass
    else:
        # 无最新数据，删除当天数据，插入当天最新数据
        delete_today_data(db_con, db_cursor, record_date)
        insert_today_data(db_con, db_cursor, record_date, last_time, today_total, today_add)

    # # 获取历史的总数据
    # day_list = json_data['chinaDayList']
    # for day_total in day_list:
    #     # 保存数据 t
    #     save_day_data(db_con, db_cursor, day_total)
    #
    # # 获取历史的新增数据
    # day_list = json_data['chinaDayAddList']
    # for day_add in day_list:
    #     update_day_data(db_con, db_cursor, day_add)

    # 获取省确诊数据
    result = get_province_today_data(db_con, db_cursor, last_time)
    if len(result) > 0:
        pass
    else:
        delete_province_today_data(db_con, db_cursor, record_date)
        province_list = json_data['areaTree'][0]['children']
        for province_data in province_list:
            save_province_data(db_con, db_cursor, record_date, province_data, last_time)


if __name__ == '__main__':
    main()
